/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/*
 * TroopsSaveDialog.java
 *
 * Created on 01.08.2009, 18:58:20
 */
package de.tor.tribes.dssim.ui;

import de.tor.tribes.dssim.io.SimIOHelper;
import de.tor.tribes.dssim.model.SimulatorTableModel;
import de.tor.tribes.dssim.types.AbstractUnitElement;
import de.tor.tribes.dssim.types.UnitHolder;
import java.io.File;
import java.util.Arrays;
import java.util.Hashtable;
import java.util.List;
import javax.swing.DefaultListModel;
import javax.swing.JOptionPane;

/**
 *
 * @author Charon
 */
public class TroopsLoadDialog extends javax.swing.JDialog {

    private final int LOAD_OFF_TYPE = 0;
    private final int LOAD_DEF_TYPE = 1;
    private static TroopsLoadDialog SINGLETON = null;
    private int type = LOAD_OFF_TYPE;

    public static synchronized TroopsLoadDialog getSingleton() {
        if (SINGLETON == null) {
            SINGLETON = new TroopsLoadDialog(DSWorkbenchSimulatorFrame.getSingleton(), true);
        }
        return SINGLETON;
    }

    public void showLoadDefDialog() {
        setTitle("Deff laden");
        type = LOAD_DEF_TYPE;
        buildSetupList();
        setLocationRelativeTo(DSWorkbenchSimulatorFrame.getSingleton());
        setVisible(true);
    }

    public void showLoadOffDialog() {
        setTitle("Off laden");
        type = LOAD_OFF_TYPE;
        buildSetupList();
        setLocationRelativeTo(DSWorkbenchSimulatorFrame.getSingleton());
        setVisible(true);
    }

    private void buildSetupList() {
        DefaultListModel model = new DefaultListModel();
        String[] setups = null;
        if (type == LOAD_OFF_TYPE) {
            setups = SimIOHelper.getOffSetups().toArray(new String[]{});
        } else {
            setups = SimIOHelper.getDefSetups().toArray(new String[]{});
        }
        Arrays.sort(setups);
        for (String setup : setups) {
            model.addElement(setup);
        }
        jTroopSetupList.setModel(model);
        jTroopSetupList.setSelectedIndex(0);
    }

    /** Creates new form TroopsSaveDialog */
    TroopsLoadDialog(java.awt.Frame parent, boolean modal) {
        super(parent, modal);
        initComponents();
    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jLabel1 = new javax.swing.JLabel();
        jLoadButton = new javax.swing.JButton();
        jButton2 = new javax.swing.JButton();
        jScrollPane1 = new javax.swing.JScrollPane();
        jTroopSetupList = new javax.swing.JList();
        jButton1 = new javax.swing.JButton();

        setAlwaysOnTop(true);
        setModal(true);

        jLabel1.setText("Bezeichnung");

        jLoadButton.setText("Laden");
        jLoadButton.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                fireCloseEvent(evt);
            }
        });

        jButton2.setText("Abbrechen");
        jButton2.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                fireCloseEvent(evt);
            }
        });

        jTroopSetupList.setModel(new javax.swing.AbstractListModel() {
            String[] strings = { "Item 1", "Item 2", "Item 3", "Item 4", "Item 5" };
            public int getSize() { return strings.length; }
            public Object getElementAt(int i) { return strings[i]; }
        });
        jScrollPane1.setViewportView(jTroopSetupList);

        jButton1.setText("Löschen");
        jButton1.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                fireDeleteSetupEvent(evt);
            }
        });

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(jLabel1)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 171, Short.MAX_VALUE))
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                        .addComponent(jButton2)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED, 12, Short.MAX_VALUE)
                        .addComponent(jButton1)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(jLoadButton)))
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jLabel1)
                    .addComponent(jScrollPane1))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLoadButton)
                    .addComponent(jButton2)
                    .addComponent(jButton1))
                .addContainerGap())
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void fireCloseEvent(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_fireCloseEvent
        String name = (String) jTroopSetupList.getSelectedValue();

        if (evt.getSource() == jLoadButton) {
            if (name == null) {
                JOptionPane.showMessageDialog(this, "Bitte einen Eintrag auswählen.", "Warnung", JOptionPane.WARNING_MESSAGE);
                return;
            }

            if (type == LOAD_OFF_TYPE) {
                //save off
                name = name + "_off.xml";
            } else {
                //save def
                name = name + "_def.xml";
            }
            List<AbstractUnitElement> elements = null;
            try {
                elements = SimIOHelper.readTroopSetup(SimIOHelper.getDataDir() + "/" + name);
                Hashtable<UnitHolder, AbstractUnitElement> setup = new Hashtable<UnitHolder, AbstractUnitElement>();
                for (AbstractUnitElement element : elements) {
                    setup.put(element.getUnit(), element);
                }
                if (type == LOAD_OFF_TYPE) {
                    SimulatorTableModel.getSingleton().setOff(setup);
                } else {
                    SimulatorTableModel.getSingleton().setDef(setup);
                }
            } catch (Exception e) {
                JOptionPane.showMessageDialog(this, "Fehler beim Laden der Truppen. (Grund: " + e.getMessage() + ")", "Fehler", JOptionPane.ERROR_MESSAGE);
                setVisible(false);
                return;
            }
        }
        setVisible(false);
    }//GEN-LAST:event_fireCloseEvent

    private void fireDeleteSetupEvent(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_fireDeleteSetupEvent
        String name = (String) jTroopSetupList.getSelectedValue();
        if (name == null) {
            JOptionPane.showMessageDialog(this, "Bitte einen Eintrag auswählen.", "Warnung", JOptionPane.WARNING_MESSAGE);
            return;
        }

        if (type == LOAD_OFF_TYPE) {
            //save off
            name = name + "_off.xml";
        } else {
            //save def
            name = name + "_def.xml";
        }


        if (new File(SimIOHelper.getDataDir() + "/" + name).delete()) {
            buildSetupList();
        } else {
            JOptionPane.showMessageDialog(this, "Eintrag konnte nicht gelöscht werden.", "Fehler", JOptionPane.ERROR_MESSAGE);
        }

    }//GEN-LAST:event_fireDeleteSetupEvent

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        java.awt.EventQueue.invokeLater(new Runnable() {

            public void run() {
                TroopsLoadDialog dialog = new TroopsLoadDialog(new javax.swing.JFrame(), true);
                dialog.addWindowListener(new java.awt.event.WindowAdapter() {

                    public void windowClosing(java.awt.event.WindowEvent e) {
                        System.exit(0);
                    }
                });
                dialog.setVisible(true);
            }
        });
    }

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton jButton1;
    private javax.swing.JButton jButton2;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JButton jLoadButton;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JList jTroopSetupList;
    // End of variables declaration//GEN-END:variables
}
